package com.sherlockHolmes.init.recommend;

import com.sherlockHolmes.init.base.result.Ajax;
import com.sherlockHolmes.init.base.utils.IPUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

@Component
public class PeopleNearby {
    @Resource
    private RedisTemplate redisTemplate;
    @ApiOperation(value = "手机上线，报告经纬度")
    public Ajax online(String name,String ip) throws Exception {
        Double longitude = IPUtils.getLongitude(ip);
        Double latitude = IPUtils.getLatitude(ip);
        redisTemplate.opsForGeo().add("geo", new Point(longitude, latitude), name);
        return Ajax.success();
    }
    @ApiOperation(value = "获取成员间距离")
    public Distance geodist(String member1, String member2) {
        //获取两个成员间距离，单位km
        Distance distance = this.redisTemplate.opsForGeo().distance("geo", member1, member2, RedisGeoCommands.DistanceUnit.KILOMETERS);
        return distance;
    }
    @ApiOperation(value = "获取成员附近的人")
    public GeoResults radiusByMember(String member,double range,Metrics unit) {
        //返回结果按距离升序，包含距离和经纬度, 返回50条
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands
                .GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending().limit(50);
        //半径10公里内
        Distance distance = new Distance(range, unit);
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.redisTemplate
                .opsForGeo()
                .radius("geo", member, distance, args);
        return geoResults;
    }
    @ApiOperation(value = "获取指定经纬度附近的人")
    public GeoResults georadius(double longitude, double latitude) {
        //半径10公里内
        Distance distance = new Distance(10, Metrics.KILOMETERS);
        //根据经纬度生成范围
        Circle circle = new Circle(new Point(longitude, latitude), distance);
        //返回结果按距离升序，包含距离和经纬度, 返回50条
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands
                .GeoRadiusCommandArgs
                .newGeoRadiusArgs()
                .includeDistance()
                .includeCoordinates()
                .sortAscending().limit(50);
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = this.redisTemplate
                .opsForGeo()
                .radius("geo", circle, args);
        return geoResults;
    }

}
